package com.boot.dog.web.security.handler;

import com.alibaba.fastjson.JSON;
import com.boot.dog.common.constant.SecurityConst;
import com.boot.dog.common.annotation.SysLog;
import com.boot.dog.common.enums.LogType;
import com.boot.dog.common.auth.DogUser;
import com.boot.dog.web.security.util.SecurityResult;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Value("${security.jwt.token.expire-length:3600000}")
    private long validityInMilliseconds;

    @Override
    @SysLog(desc = "登录系统", type = LogType.LOGIN)
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) {
        DogUser dogUser = ((DogUser) authentication.getPrincipal());
        List<String> authorities = ((DogUser) authentication.getPrincipal())
                .getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        String token = SecurityConst.TOKEN_SPLIT + Jwts.builder()
                .setSubject(dogUser.getUsername())
                .claim(SecurityConst.USER_TYPE, dogUser.getUsertype())
                .claim(SecurityConst.AUTHORITIES, JSON.toJSONString(authorities))
                .setExpiration(new Date(System.currentTimeMillis() + validityInMilliseconds))
                .signWith(SignatureAlgorithm.HS512, SecurityConst.JWT_SIGN_KEY).compact();
        SecurityResult.success(response, "登录成功", token);
    }
}
